package com.roc.web.action.windcontroll;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMgmRiskRule;
import com.roc.service.RiskRuleMgrService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.RiskRuleAboutAll;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/windControllSta")
public class RiskRuleMgrAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(RiskRuleMgrAction.class);
	
	@Autowired
	private RiskRuleMgrService riskRuleMgrService;
	
	private RiskRuleMgrSearchCondition searchCondition;
	
	private String paramsStr;
	private String paramMchtCd;
	private String paramRiskLevel;
	private String paramsPosType;
	
	@Autowired
	private IPageService pagenitionService;
	
	@Action(value="queryRiskRuleJsp",results={ @Result(name="success",location="/pages/windControllSta/queryRiskRuleJsp.jsp")})
	public String queryRiskRuleJsp(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		return SUCCESS;
		}
	
	@Action(value="queryRiskRuleList",results={ @Result(name="success",location="/pages/windControllSta/queryRiskRuleJsp.jsp")})
	public String queryRiskRule(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		if(searchCondition==null){
			searchCondition=(RiskRuleMgrSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new RiskRuleMgrSearchCondition();
			}
		}
		try {
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<TblMgmRiskRule> riskRuleList = new ArrayList<TblMgmRiskRule>();
			dealTheSearchRsList(riskRuleList,searchRsList);
		
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, riskRuleList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.error("查询风控规则异常：{}",e);
		}
		return SUCCESS;
	}
	
	@Action(value="updateRiskRule")
	public String updateRiskRule(){
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		try {
			boolean flag = riskRuleMgrService.modifyRiskRule(paramsStr,logingMerchant);
			
			if(flag == true){
				jsonObject.put("flag", flag);
				jsonObject.put("message", "风控规则修改成功");
			}else{
				jsonObject.put("flag", flag);
				jsonObject.put("message", "风控规则修改失败");
			}
			out = response.getWriter();
		} catch (Exception e) {
			logger.error("修改风控规则异常:{}",e);
			jsonObject.put("flag", false);
			jsonObject.put("message", "风控规则修改异常");
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	
	@Action(value="addRiskRules")
	public String addRiskRules(){
		
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		Map<String,Object> resultMap = null;
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			resultMap = riskRuleMgrService.addRiskRules(paramMchtCd, paramRiskLevel,paramsPosType, logingMerchant);
			out = response.getWriter();
			jsonObject.put("resultMap", resultMap);
		} catch (Exception e) {
			logger.error("风控规则添加异常",e);
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
 
	private void dealTheSearchRsList(List<TblMgmRiskRule> riskRuleList,
			List<Object> searchRsList) {
		if(searchRsList != null && searchRsList.size() > 0){
			Iterator<Object> it = searchRsList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				TblMgmRiskRule risk = new TblMgmRiskRule();
				risk.setRiskLevel(Constance.Null2EmptyTrim(obj[0]));
				risk.setRiskInsCd(Constance.Null2EmptyTrim(obj[1]));
				risk.setRiskMchtCd(Constance.Null2EmptyTrim(obj[2]));
				risk.setRiskTermCd(Constance.Null2EmptyTrim(obj[3]));
				risk.setRiskTransType(Constance.Null2EmptyTrim(obj[4]));
				risk.setRiskInfoType(Constance.Null2EmptyTrim(obj[5]));
				risk.setRiskNumCycle(Constance.Null2EmptyTrim(obj[6]));
				risk.setRiskKeyType(Constance.Null2EmptyTrim(obj[7]));
				risk.setRiskNumType(Constance.Null2EmptyTrim(obj[8]));
				risk.setRiskNumUnite(Constance.Null2EmptyTrim(obj[9]));
				risk.setRiskNumValue(Constance.Null2EmptyTrim(obj[10]));
				risk.setRiskUse(Constance.Null2EmptyTrim(obj[11]));
				risk.setName(Constance.Null2EmptyTrim(obj[12]));
				risk.setRiskInfoTypeDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[5])).getDesc());
				risk.setRiskNumCycleDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getDesc());
				risk.setRiskKeyTypeDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[7])).getDesc());
				risk.setRiskNumTypeDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[8])).getDesc());
				risk.setRiskNumUniteDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[9])).getDesc());
				risk.setRiskUseDesc(RiskRuleAboutAll.valueOfCode(Constance.Null2EmptyTrim(obj[11])).getDesc());
				riskRuleList.add(risk);
			}
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_RISK_RULE_QUERY, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_RISK_RULE_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public RiskRuleMgrSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(RiskRuleMgrSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getParamsStr() {
		return paramsStr;
	}

	public void setParamsStr(String paramsStr) {
		this.paramsStr = paramsStr;
	}

	public String getParamMchtCd() {
		return paramMchtCd;
	}

	public void setParamMchtCd(String paramMchtCd) {
		this.paramMchtCd = paramMchtCd;
	}

	public String getParamRiskLevel() {
		return paramRiskLevel;
	}

	public void setParamRiskLevel(String paramRiskLevel) {
		this.paramRiskLevel = paramRiskLevel;
	}

	public String getParamsPosType() {
		return paramsPosType;
	}

	public void setParamsPosType(String paramsPosType) {
		this.paramsPosType = paramsPosType;
	}
	
}
